#include <iostream>
#include <thread>

#include "nanomodbus.h"
#include "../include/func.h"
#include "../include/Device.h"
#include "../include/server.h"
#include "../include/client.h"
#include <winsock2.h>

void test() {
    //TIP 当文本光标位于 <b>lang</b> 变量名称处时，按 <shortcut actionId="RenameElement"/> 可以查看 CLion 如何帮助您重命名该变量。
    const auto lang = "C++";
    std::cout << "Hello and welcome to " << lang << "!\n";

    auto *device = new Device();
    device->setName(lang);

    std::cout << "Hello and welcome to " << device->getName() << "!\n" << std::flush;

    for (int i = 1; i <= 5; i++) {
        // TIP 按 <shortcut actionId="Debug"/> 开始调试代码。我们已为您设置了一个 <icon src="AllIcons.Debugger.Db_set_breakpoint"/> 断点，但您可以随时按 <shortcut actionId="ToggleLineBreakpoint"/> 添加更多断点。
        std::cout << "i = " << i << std::endl;
    }

    delete device;

    // std::thread t(start_http);
    // t.detach();
}


// 自定义平台读写函数（修复版本）
int32_t my_transport_read(uint8_t *buf, uint16_t count, int32_t timeout_ms, void *conn) {
    // 正确地将conn指针转换为SOCKET，而不是取conn的地址
    if (conn == nullptr) {
        std::cerr << "[ERROR] Connection pointer is null in transport_read\n";
        return -1;
    }
    return tcp_read(*(SOCKET *) conn, buf, count, timeout_ms);
}

int32_t my_transport_write(const uint8_t *buf, uint16_t count, int32_t timeout_ms, void *conn) {
    // 正确地将conn指针转换为SOCKET，而不是取conn的地址
    if (conn == nullptr) {
        std::cerr << "[ERROR] Connection pointer is null in transport_write\n";
        return -1;
    }
    return tcp_write(*(SOCKET *) conn, buf, count, timeout_ms);
}

void test_modbus() {
    std::cout << "Starting Modbus TCP client test...\n";

    // 1. 初始化平台配置
    nmbs_platform_conf platform_conf;
    nmbs_platform_conf_create(&platform_conf);
    platform_conf.transport = NMBS_TRANSPORT_TCP;
    platform_conf.read = my_transport_read;
    platform_conf.write = my_transport_write;

    // 2. 创建并连接TCP客户端
    SOCKET client_socket = INVALID_SOCKET;
    WSADATA ws;

    // 初始化Winsock
    if (WSAStartup(MAKEWORD(2, 2), &ws) != 0) {
        std::cerr << "[ERROR] WSAStartup failed with error: " << WSAGetLastError() << std::endl;
        return;
    }

    // 创建socket
    client_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (client_socket == INVALID_SOCKET) {
        std::cerr << "[ERROR] Socket creation failed with error: " << WSAGetLastError() << std::endl;
        WSACleanup();
        return;
    }

    // 设置服务器地址
    sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); // 服务器IP地址
    server_addr.sin_port = htons(502); // Modbus默认端口

    // 连接服务器
    if (connect(client_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
        std::cerr << "[ERROR] Connect failed with error: " << WSAGetLastError() << std::endl;
        std::cerr << "Make sure Modbus TCP server is running on 127.0.0.1:502" << std::endl;
        closesocket(client_socket);
        WSACleanup();
        return;
    }

    std::cout << "Successfully connected to Modbus TCP server\n";

    // 设置连接参数
    platform_conf.arg = &client_socket;

    // 3. 创建客户端实例
    nmbs_t nmbs;
    if (nmbs_client_create(&nmbs, &platform_conf) != NMBS_ERROR_NONE) {
        std::cerr << "[ERROR] Failed to create Modbus client\n";
        closesocket(client_socket);
        WSACleanup();
        return;
    }

    // 4. 设置Modbus从站ID
    nmbs_set_destination_rtu_address(&nmbs, 1);

    // 5. 批量写入2个寄存器（地址26）
    unsigned short write_data[2] = {123, 124};
    std::cout << "Writing registers 26-27 with values 123, 124...\n";

    nmbs_error write_result = nmbs_write_multiple_registers(&nmbs, 800, 2, write_data);
    if (write_result != NMBS_ERROR_NONE) {
        std::cerr << "[ERROR] Write registers failed with error code: " << write_result << std::endl;
        std::cout << "ERROR wrote registers\n";
    } else {
        std::cout << "Successfully wrote registers\n";

        // 6. 读取验证
        uint16_t read_data[2];
        std::cout << "Reading registers 26-27 to verify...\n";

        nmbs_error read_result = nmbs_read_holding_registers(&nmbs, 800, 2, read_data);
        if (read_result != NMBS_ERROR_NONE) {
            std::cerr << "[ERROR] Read registers failed with error code: " << read_result << std::endl;
        } else {
            std::cout << "Successfully read registers. Values: " << read_data[0] << ", " << read_data[1] << std::endl;
        }
    }

    // 清理资源
    closesocket(client_socket);
    WSACleanup();
    std::cout << "Modbus TCP client test completed\n";
}

void callBack(int (*p)(int, int)) {
    p(1, 2);
}

struct A {
    int16_t a;
    int16_t b;
    int c;
    int d;
};

int main() {
    // callBack([](int a, int b) {
    //     std::cout << "a = " << a << ", b = " << b << std::endl;
    //     return a + b;
    // });
    startTcpServer();
    // test_modbus();
    // A a = {.a = 1, .b = 2};
    // const A *c = new A(5, 6);
    // A b[] = {a, {2, 6}, *c};
    // std::cout << sizeof(a) << std::endl;
    // callBack([](const int a, const int b) {
    //     return a + b;
    // });
    // delete c;
    int a {1};
    int* b = new int(2);
    int& c = a;
    char d[] = "123";
    std::cout << d[2] << std::endl;
}
